package yimei

import (
	"crypto/md5"
	"encoding/hex"
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net/http"
	"time"
)
/*
* SUCCESS
* ERROR_APPID          AppId错误
* ERROR_CLIENT_IP      不识别的Ip
* ERROR_OVER_SPEED     请求超速
* ERROR_MOBILE_EMPTY   手机号为空
* ERROR_MOBILE_NUMBER  号码数量过多
* ERROR_MOBILE_ERROR   手机号码错误
* ERROR_CONTENT_EMPTY  短信内容为空
* ERROR_LONG_CONTENT   短信内容过长
* ERROR_BALANCE        余额不足
* ERROR_TIMESTAMP      时间戳错误
* ERROR_SIGN           签名错误
*/
var (
	SUCCESS = "SUCCESS"
	SERVER_HOST = "http://www.btom.cn:8080/simpleinter/sendSMS"
)

type Config struct {
	AppId string `json:"appId"`
	Passwd string `json:"passwd"`
}
type Result struct {
	Code string `json:"code"`
	Msg string `json:"msg"`
}
type YiMei struct {
	conf *Config
}

func NewYiMei(appId string,passwd string) *YiMei{
	conf := Config{
		AppId:  appId,
		Passwd: passwd,
	}
	return &YiMei{conf: &conf}
}

func (y *YiMei) Send(orderId string,mobiles string,content string) (msgId string, err error) {
	now := time.Now()
	tm := now.Format("2006-01-02 15:04:05.000")
	msign := fmt.Sprintf("%s%s%s",y.conf.AppId,y.conf.Passwd,tm)
	h := md5.New()
	h.Write([]byte(msign))
	sign := hex.EncodeToString(h.Sum(nil))
	req, err := http.NewRequest("GET", SERVER_HOST, nil)
	if err != nil {
		return
	}
	q := req.URL.Query()
	q.Add("sign",sign)
	q.Add("content",content)
	q.Add("appId",y.conf.AppId)
	q.Add("timestamp",tm)
	q.Add("mobiles",mobiles)
	client := http.Client{
		Timeout: time.Second * 3,
	}
	resp, err := client.Do(req)
	if err != nil {
		return
	}
	defer resp.Body.Close()
	body, err := ioutil.ReadAll(resp.Body)
	fmt.Println(string(body))
	if err != nil {
		return
	}
	fmt.Println("body-------------",string(body))
	var result Result
	err = json.Unmarshal(body,&result)
	if err != nil {
		return
	}
	if result.Code == SUCCESS {
		return
	}
	err = fmt.Errorf("%s",result.Code)
	return
}
